package org.example.command;

import org.example.model.HTMLDocument;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;

public class PrintIndentCommand implements Command {
    private HTMLDocument htmlDocument;
    private int indent;

    private PrintIndentCommand(HTMLDocument htmlDocument, int indent) {
        this.htmlDocument = htmlDocument;
        this.indent = indent;
    }

    public static PrintIndentCommand create(HTMLDocument htmlDocument, int indent) {
        return new PrintIndentCommand(htmlDocument, indent);
    }

    @Override
    public boolean execute() {
        Element rootElement = htmlDocument.getDocument().child(0);  // 从 <html> 开始
        printElement(rootElement, 0);  // 递归打印 HTML 树结构
        return true;
    }

    /**
     * 递归打印元素，自动处理缩进和单行文本的情况
     *
     * @param element 当前处理的元素
     * @param currentIndent 当前缩进级别
     */
    private void printElement(Element element, int currentIndent) {
        // 获取缩进空格
        String indentSpace = " ".repeat(currentIndent * indent);

        // 打印开始标签
        System.out.print(indentSpace + "<" + element.tagName());

        // 打印属性
        element.attributes().asList().forEach(attr -> {
            System.out.print(" " + attr.getKey() + "=\"" + attr.getValue() + "\"");
        });
        System.out.print(">");

        // 检查该元素是否只有一个文本子节点
        if (element.children().isEmpty() && element.childNodes().size() == 1 && element.childNode(0) instanceof TextNode) {
            // 该元素只有一个文本子节点时，直接在同一行打印文本内容
            System.out.print(((TextNode) element.childNode(0)).text());
            System.out.println("</" + element.tagName() + ">");
        } else {
            // 否则，换行打印子节点
            System.out.println();
            for (Node child : element.childNodes()) {
                if (child instanceof Element) {
                    printElement((Element) child, currentIndent + 1);  // 递归处理子元素
                } else if (child instanceof TextNode) {
                    // 处理文本节点，去除多余的空白
                    String text = ((TextNode) child).text().trim();
                    if (!text.isEmpty()) {
                        System.out.println(indentSpace + " ".repeat(indent) + text);
                    }
                }
            }
            // 打印结束标签
            System.out.println(indentSpace + "</" + element.tagName() + ">");
        }
    }
}
